import { useAxios } from '@/hooks/useAxios'
import { IUser } from '@/type/user'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { AxiosError } from 'axios'
import { toast } from 'sonner'

export const useGetCurrenUserQuery = () => {
  const { axiosInstance } = useAxios()
  return useQuery<IUser, AxiosError>({
    queryKey: ['useGetCurrenUserQuery'],
    queryFn: async () => {
      const response = await axiosInstance.get('/user/current')
      return response.data
    }
  })
}

export const useGetUserQuery = (id: number) => {
  const { axiosInstance } = useAxios()
  return useQuery<IUser, AxiosError>({
    queryKey: ['useGetUserQuery'],
    queryFn: async () => {
      const response = await axiosInstance.get(`/user/info/${id}`)
      return response.data
    }
  })
}

//更新用户资料
export const useUpdateUserMutation = () => {
  const { axiosInstance } = useAxios()
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: async (data: IUser) => {
      const response = await axiosInstance.put('/user', data)
      queryClient.invalidateQueries({ queryKey: ['useGetCurrenUserQuery'] })
      toast('资料更新成功')
      return response.data
    }
  })
}

//更新用户密码
export const useUpdatePasswordMutation = <T>() => {
  const { axiosInstance } = useAxios()
  return useMutation({
    mutationFn: async (data: T) => {
      const response = await axiosInstance.put('/user/password', data)
      toast('密码更新成功')
      return response.data
    }
  })
}

//绑定邮箱
export const useBindEmailMutation = <T>() => {
  const { axiosInstance } = useAxios()
  return useMutation({
    mutationFn: async (data: T) => {
      const response = await axiosInstance.post('/user/bind/email', data)
      toast('邮箱绑定成功')
      return response.data
    }
  })
}

//绑定手机号
export const useBindMobileMutation = <T>() => {
  const { axiosInstance } = useAxios()
  return useMutation({
    mutationFn: async (data: T) => {
      const response = await axiosInstance.post('/user/bind/mobile', data)
      toast('手机绑定成功')
      return response.data
    }
  })
}
